<template>
  <div id="modify-geometry-map" style="width: 100%; height: 100%;"></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import { XYZ } from 'ol/source';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import LineString from 'ol/geom/LineString';
import Polygon from 'ol/geom/Polygon';
import { Style, Fill, Stroke, Circle as CircleStyle } from 'ol/style';
import { Select } from 'ol/interaction';
import Modify from 'ol/interaction/Modify';
import { defaults as DefaultControls } from 'ol/control';

let map: Map | null = null;
let selectInteraction: Select | null = null;
let modifyInteraction: Modify | null = null;

onMounted(() => {
  const vectorSource = new VectorSource({
    features: [
      new Feature(new Point([114.30, 30.50])),
      new Feature(new LineString([[114.20, 30.40], [114.40, 30.60]])),
      new Feature(new Polygon([[[114.10, 30.30], [114.50, 30.30], [114.50, 30.70], [114.10, 30.70], [114.10, 30.30]]])),
    ],
  });

  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0.2)',
      }),
      stroke: new Stroke({
        color: '#ffcc33',
        width: 3,
      }),
      image: new CircleStyle({
        radius: 7,
        fill: new Fill({
          color: '#ffcc33',
        }),
      }),
    }),
  });

  map = new Map({
    controls: DefaultControls({
      zoom: false,
      rotate: false,
      attribution: false,
    }).extend([]),
    target: 'modify-geometry-map',
    layers: [
      new TileLayer({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', // 高德地图
        }),
      }),
      vectorLayer,
    ],
    view: new View({
      center: [114.30, 30.50],
      zoom: 12,
      projection: 'EPSG:4326', // 使用经纬度坐标系
    }),
  });

  // Select interaction
  selectInteraction = new Select();
  map.addInteraction(selectInteraction);

  // Modify interaction
  modifyInteraction = new Modify({
    features: selectInteraction.getFeatures(),
  });
  map.addInteraction(modifyInteraction);

  console.log("ModifyGeometryMap mounted.");
});

onUnmounted(() => {
  if (map) {
    map.setTarget(undefined);
    map = null;
  }
  if (selectInteraction) {
    selectInteraction.dispose();
    selectInteraction = null;
  }
  if (modifyInteraction) {
    modifyInteraction.dispose();
    modifyInteraction = null;
  }
  console.log("ModifyGeometryMap unmounted.");
});
</script>

<style scoped>
#modify-geometry-map {
  width: 100%;
  height: 100%;
}
</style> 